package com.hxut.mrs.handler;

import com.alibaba.fastjson.JSON;
import com.hxut.mrs.common.ResponseResult;
import com.hxut.mrs.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * description: AuthenticationEntryPointImpl
 * date: 2022/7/8 22:21
 * author: MR.孙
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //处理认证异常
        ResponseResult result =
                new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"用户认证失败请重新登录");
        //将responseResult转成json字符串
        String json = JSON.toJSONString(result);
        //写入响应体中
        WebUtils.renderString(httpServletResponse,json);

    }
}
